package dataHardware;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Statement;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class Sensor {
	private String ID;
	private Properties stringFormat;
	private String separator;
	private int separatorLength;
	private int IDLength;
	private int valueLength;
	private Modem modem;
	private int timeInterval;
	public Sensor(String ID, Modem modem, int timeInterval){
		this.modem = modem;
		this.ID = ID;
		stringFormat = new Properties();
		try {
			stringFormat.load(new 
					FileInputStream("properties/stringFormat.properties"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		separator = stringFormat.getProperty("Symbol");
		separatorLength = Integer.parseInt(
				stringFormat.getProperty("Separator"));
		IDLength = Integer.parseInt(stringFormat.getProperty("ID"));
		valueLength = Integer.parseInt(stringFormat.getProperty("Value"));
		this.timeInterval = timeInterval;
	}
	
	private void sendToModem(){
		Random rm = new Random();
		Double value = rm.nextDouble()*100;
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		DataOutputStream datastream = new DataOutputStream(bytestream);
		try {
			datastream.writeBytes(separator);
			datastream.writeBytes(ID);
			datastream.writeDouble(value);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] bytes = bytestream.toByteArray();
		modem.acceptBytes(bytes);
	}
	
	public void startTimerAt(Date firstTime){
		Timer timer = new Timer(true);
		TimerTask task = new TimerTask(){
			public void run(){
				sendToModem();
			}
		};
		timer.schedule(task, firstTime, timeInterval);
	}
	public static void main(String [] args){
		Random rm = new Random();
		Double value = rm.nextDouble()*1000;
		
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		DataOutputStream datastream = new DataOutputStream(bytestream);
		try {
			datastream.writeBytes("@#*");
			datastream.writeBytes("031");
			datastream.writeDouble(value);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] bArray = bytestream.toByteArray();
		System.out.println("Double is: "+value);
		System.out.println("array length is: "+bArray.length);
		for (byte b:bArray){
			
			System.out.printf("%s\n",Integer.toString(b&0xff, 16).toUpperCase());
		}
		
		
		
	}
	
}
